/**
 * 
 */
package com.armail.client.controller.impl;

import java.util.Collection;
import java.util.LinkedHashSet;

import javax.ws.rs.core.MediaType;

import com.armail.client.ARMailApp;
import com.armail.client.controller.LoginController;
import com.armail.client.controller.LoginControllerListener;
import com.armail.client.di.Context;
import com.armail.client.dto.User;
import com.armail.client.view.LoginView;
import com.armail.client.view.LoginViewListener;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

/**
 * @author arpit
 *
 */
public class LoginControllerImpl extends ControllerImpl implements LoginController, LoginViewListener {
	
	private final LoginView loginView;
	private User model;
	private final Collection<LoginControllerListener> listeners = new LinkedHashSet<LoginControllerListener>();

	@Inject
	public LoginControllerImpl(Injector injector, LoginView loginView) {
		super(injector);
		this.loginView = loginView;
		loginView.addListener(this);
	}

	private static final String REST_URI = "http://localhost:8080/com-armail-server/";
	private static final String GET_USER = "/users/findByUserName/";
	
	@Override
	public void onClickLogin() {
		ClientConfig config = new DefaultClientConfig();  
        Client client = Client.create(config);  
        WebResource resource = client.resource(REST_URI);  
        
        WebResource employeeResource = resource.path("/rest/").path(GET_USER).path(model.getUserName()); 
        final ClientResponse response = employeeResource.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
        User user = response.getEntity(User.class);
        Context.setUser(user);
        for (LoginControllerListener l : listeners) {
			l.onSuccessfulLogin();
		}
        ARMailApp.getInstance().getStage().setTitle("ARMail - "+user.getFirstName()+" "+user.getLastName());
	}

	@Override
	public void activate() {
		this.model = new User();
		loginView.setModel(model);
		loginView.attach();
	}

	@Override
	public void deactivate() {
		// TODO Auto-generated method stub
	}

	public User getModel() {
		return model;
	}

	@Override
	public void addListener(LoginControllerListener loginControllerListener) {
		this.listeners.add(loginControllerListener);
	}

	@Override
	public void removeListener(LoginControllerListener loginControllerListener) {
		this.listeners.remove(loginControllerListener);
	}

	@Override
	public void onClickRegister() {
		for (LoginControllerListener l : listeners) {
			l.onClickRegister();
		}
	}
}
